package com.example.viewpager2

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.RequiresApi

class MyEraseView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {


    private var resultBitmap :Bitmap ?= null
    private var srcBitmap :Bitmap?=null
    private var dstBitmap : Bitmap?=null
    private val path  = Path()
    private var dstCanvas :Canvas ?= null

    val paint = Paint().apply {
        color = Color.RED
        isAntiAlias = true
        style = Paint.Style.FILL
        strokeWidth = 60f
    }

    init {

        resultBitmap = BitmapFactory.decodeResource(resources,R.drawable.result)
        srcBitmap = BitmapFactory.decodeResource(resources,R.drawable.eraser)

        srcBitmap?.let {
            //目标图像
            dstBitmap = Bitmap.createBitmap(it.width,it.height,Bitmap.Config.ARGB_8888)
        }


        //绑定canvas和bitmap
        dstBitmap?.let {
            dstCanvas = Canvas(it)
        }
        path.reset()


    }

    private var radio = 0f

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            //绘制刮奖结果
            drawBitmap(resultBitmap!!, 0f, 0f, paint)
            val saveLayer = saveLayer(0f, 0f, width.toFloat(), height.toFloat(), paint)
            //绘制目标bitmap
//            dstCanvas?.drawPath(path,paint)
            dstCanvas?.drawCircle(width/2f,height/2f,radio,paint)

            drawBitmap(dstBitmap!!,0f,0f,paint)
            //设置paint 画笔
            paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC_OUT))
            drawBitmap(srcBitmap!!,0f,0f,paint)
            paint.setXfermode(null)
            restoreToCount(saveLayer)
        }
    }


    private var evenX = 0f
    private var evenY = 0f
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.apply {
            when(action){
                MotionEvent.ACTION_DOWN->{
                    evenX  = x
                    evenY = y
                    path.moveTo(evenX,evenY)
                    radio = 50f

                    invalidate()
                    return true
                }
                MotionEvent.ACTION_MOVE->{
                    val endX: Float = (event.x - evenX) / 2 + evenX
                    val endY: Float = (event.y - evenY) / 2 + evenY
                    //画二阶贝塞尔曲线
                    //画二阶贝塞尔曲线
                    path.quadTo(evenX, evenY, endX, endY)
                    evenX = event.x
                    evenY = event.y
                    invalidate()
                    return true
                }
            }

        }

        return super.onTouchEvent(event)

    }

}